﻿using Aker.DevTeam;
using Aker.Properties;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;


namespace Aker.Iplik
{
    public partial class Iplikler : XForm
    {
        List<int> selectedRows = new List<int>();

        string imageBackupPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AkerPhotos\\Iplik";
        DataTable dtIplik = null;

        public Iplikler()
        {
            InitializeComponent();
        }

        void Iplikler_Load(object sender, EventArgs e)
        {
            DataSet ds = Data.DM.ExecuteDataSet("GetIplikSatilanStok");
            dtIplik = ds.Tables[0];

            BindingSource bs = new BindingSource(ds, ds.Tables[0].TableName);
            dtIplik.Columns.Add("Seç", typeof(Boolean));
            dtIplik.Columns.Add("Sira", typeof(int));

            dtIplik.Columns["Seç"].SetOrdinal(0);
            dtIplik.Columns["Sira"].SetOrdinal(1);
            foreach (DataRow dr in dtIplik.Rows)
                dr["Seç"] = false;
            dtIplik.AcceptChanges();


            gv.Init(bs);
            gv.ViewCaption = "İplik Stoğu (Grup+Tedarikçi+Renk)";
            gv.SetCaptions("Sira:Sıra", "PesinFiyat:Peşin Fiyat", "Tedarikci:Tedarikçi", "FiiliIstanbul:Fiili İstanbul", "FiiliBilecik:Fiili Bilecik", "IstanbulBilecik:İstanbul>Bilecik", "BilecikIstanbul:Bilecik>İstanbul", "RafsizGirisKG:Belirsiz");
            gv.FormatAsNumber("FiiliIstanbul", "FiiliBilecik", "IstanbulBilecik", "BilecikIstanbul", "RafsizGirisKG");
            gv.MakeColumnInvisible("GrupKodu");
            gv.AddSummary("FiiliIstanbul", "FiiliBilecik", "IstanbulBilecik", "LotAdedi", "BilecikIstanbul", "RafsizGirisKG");
            gv.MakeReadOnly();
            gv.BestFitColumns();


            gv.EnableComplexFiltering("Grup", "StokKodu");

            gv.SetCaptions();


            gv.FormatAsNumber("KG", "EskiKG", "CikisKG", "FiiliKG", "PesinFiyat", "VadeliFiyat", "Fiyat");
            gv.MakeReadOnly("PesinFiyat", "VadeliFiyat");

            gv.OptionsView.ShowViewCaption = false;

            GridMenu gmProduct = GridManager.GetManager(gv).GridMenu;

            gmProduct.AddMenu("Seçime ekle", AddToSelection);
            gmProduct.AddMenu("Seçimden çıkar", RemoveFromSelection);

            gmProduct.AddMenu("Sipariş oluştur", CreatePOrder, Resources.newPencil, true);
            gmProduct.AddMenu("İplikleri kopyala", CopyIpliks);

            gv.BestFitColumns();

            gv.RowCellClick += gvIplik_RowCellClick;
            gv.RowStyle += gvIplik_RowStyle;
            gv.RowCellStyle += gvProduct_RowCellStyle;

            colored.AddRange(new string[] { "KG", "CuvalBot", "CikisKG", "CikisCuvalBot", "FiiliKG", "FiiliCuvalBot" });
            editable.AddRange(new string[] { "PesinFiyat", "VadeliFiyat" });
        }


        List<string> colored = new List<string>();
        List<string> editable = new List<string>();

        public static DataTable KopyalanmisIplikler = new DataTable();
        private void CopyIpliks(object sender, EventArgs e)
        {
            KopyalanmisIplikler = dtIplik.Select("Sira > 0").CopyToDataTable();
            ShowInfo("İplikler kopyalandı.");
        }

        void gvProduct_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (colored.Contains(e.Column.FieldName))
                {
                    int qty = e.CellValue.ToIntNN();
                    if (qty > 0)
                        e.Appearance.FontStyleDelta = FontStyle.Bold;
                    else if (qty < 0)
                        e.Appearance.ForeColor = Color.Red;
                }
                else if (editable.Contains(e.Column.FieldName))
                {
                    e.Appearance.BackColor = Color.LightYellow;
                }
            }
        }

        void gvIplik_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Seç")
                    ToggleSelection(e.RowHandle);
            }
        }

        void AddToSelection(object sender, EventArgs e)
        {
            gv.BeginUpdate();

            foreach (int rowHandle in gv.GetSelectedRows())
            {
                bool selected = (bool)gv.GetRowCellValue(rowHandle, "Select");
                if (!selected)
                    ToggleSelection(rowHandle);
            }

            gv.EndUpdate();
        }

        void CreatePOrder(object sender, EventArgs e)
        {
            DataTable dtSelectedIplik = dtIplik.Select("Sira > 0").CopyToDataTable();
            foreach (DataRow dr in dtIplik.Select("Sira > 0"))
            {
                dr["Seç"] = false;
                dr["Sira"] = DBNull.Value;
            }

            AppSession.MainForm.ShowMdiChildForm(typeof(Uretim.YeniSiparis), dtSelectedIplik);
        }

        void RemoveFromSelection(object sender, EventArgs e)
        {
            gv.BeginUpdate();

            foreach (int rowHandle in gv.GetSelectedRows())
            {
                bool selected = (bool)gv.GetRowCellValue(rowHandle, "Seç");
                if (selected)
                    ToggleSelection(rowHandle);
            }

            gv.EndUpdate();
        }

        void gvIplik_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle > -1)
                {
                    if ((bool)gv.GetRowCellValue(e.RowHandle, "Seç"))
                        e.Appearance.BackColor = Color.AliceBlue;
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        void ToggleSelection(int rowHandle)
        {
            DataRow drCurrent = gv.GetDataRow(rowHandle);

            bool selected = (bool)drCurrent["Seç"];
            gv.SetRowCellValue(rowHandle, "Seç", !selected);
            object order = dtIplik.Compute("max(Sira)", "");

            if (selected) //ÇIKAR
            {
                int silinenSira = (int)gv.GetRowCellValue(rowHandle, "Sira");
                gv.SetRowCellValue(rowHandle, "Sira", DBNull.Value);
                foreach (DataRow dr in dtIplik.Select("Sira > " + silinenSira.ToString()))
                {
                    dr["Sira"] = (int)dr["Sira"] - 1;
                }
            }
            else  //EKLE
            {
                if (order == DBNull.Value)
                    order = 1;
                else
                    order = (int)order + 1;

                gv.SetRowCellValue(rowHandle, "Sira", order);
            }
            gv.EndEditing();
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.EndEditing();
            string changes = dtIplik.SerializeChanges("GrupKodu", "PesinFiyat", "VadeliFiyat");
            if (changes != "")
            {
                Data.DM.ExecuteNonQuery("UpdSatilanIplikFiyat", changes);
                dtIplik.AcceptChanges();

                ShowInfo("Değişiklikler kaydedildi.");
            }
            else
                ShowInfo("Değişiklik yok.");
        }
    }
}